package snail19.baseDao.BaseDaoimpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import snail19.baseDao.BaseDao;

@SuppressWarnings("unchecked")
public abstract class BasedaoImpl<T> implements BaseDao<T> {
	private Class<T> clazz;
	public BasedaoImpl() {
	ParameterizedType	type  = (ParameterizedType) this.getClass().getGenericSuperclass();
	this.clazz=(Class<T>) type.getActualTypeArguments()[0];	
	
	}
	
	@Autowired
	private SessionFactory sessionfactory; 
	
	@Override
	public void saveEntity(T t) {
		//得到当前线程的session；
		sessionfactory.getCurrentSession().save(t);
	}

	@Override
	public void deleteEntity(T t) {
		sessionfactory.getCurrentSession().delete(t);
	}

	@Override
	public void updateEntity(T t) {
		sessionfactory.getCurrentSession().update(t);
	}

	@Override
	public void bachEntity(String hql, Object... objects) {
		Query query = sessionfactory.getCurrentSession().createQuery(hql);
		for(int i=0;i<objects.length;i++){
		query.setParameter(i, objects[i]);	
			
		}
		query.executeUpdate();
	}

	@Override
	public T getEntity(Serializable id) {
		return sessionfactory.getCurrentSession().get(clazz, id);
	}

	@Override
	public T loadEntity(Serializable id) {
		return sessionfactory.getCurrentSession().load(clazz, id);
	}

	@Override
	public List<T> findEntityByHQL(String hql, Object... objects) {
		Query query = sessionfactory.getCurrentSession().createQuery(hql);
		for(int i=0;i<objects.length;i++){
		query.setParameter(i, objects[i]);	
			
		}
		return query.list();
	}

}
